import React, { useEffect, useState } from 'react'
import Stats from 'stats.js'

import HighChart from './highchart'
import Dygraphs from './dygraphs'
import UPlot from './uplot'

import { mockChartList } from './mock'
import { transFormToUPlot, transForm } from './data-transform'

const cate = 2 // 0 heightchart 1 dygraphs 2 uplot
const chartConfig = [
  {
    component: HighChart
  },
  {
    component: Dygraphs,
    formatter: transForm
  },
  {
    component: UPlot,
    formatter: transFormToUPlot
  }
]
const SingleChart = chartConfig[cate].component

function callAnimate(callback) {
  return requestAnimationFrame(callback)
}

function mock() {
  let list = mockChartList({
    chartCount: 6,
    seriesCount: 5,
    pointCount: 50,
    isArea: false
  })

  const formatter = chartConfig[cate].formatter
  if (formatter) {
    list = list.map(formatter)
  }

  return list
}

function ChartPage() {
  const [chartList, setChartList] = useState([])

  useEffect(() => {
    setChartList(mock())

    function run() {
      const stats = new Stats()
      stats.showPanel(0)
      document.body.appendChild(stats.dom)

      function animate() {
        stats.begin()
        setChartList(mock())
        stats.end()
        callAnimate(animate)
      }
      callAnimate(animate)
    }
    run()
  }, [])

  return pug`
    .box.box-wrap
      each item, index in chartList
        SingleChart(series=item.series id=item.title key=item.title)
  `
}

export default ChartPage
